#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"

ListNode* new_node(LTDataType x)
{
	ListNode* s = (ListNode*)malloc(sizeof(ListNode));
	if (s == NULL)
	{
		perror("ListPushBack::");
		return NULL;
	}
	s->_data = x;
	return s;
}

// 创建返回链表的头结点.
ListNode* ListCreate()
{
	ListNode* L = (ListNode*)malloc(sizeof(ListNode));
	if (L == NULL)
	{
		perror("ListNode::");
		return NULL;
	}
	L->_next = L->_prev = L;
	return L;
}

// 双向链表销毁
void ListDestory(ListNode* pHead)
{
	assert(pHead);
	pHead->_prev->_next = NULL;
	ListNode* p = pHead->_next;
	ListNode* q = NULL;
	free(pHead);
	pHead = NULL;
	while (p)
	{
		q = p->_next;
		free(p);
		p = q;
	}
}

// 双向链表打印
void ListPrint(ListNode* pHead)
{
	ListNode* p = pHead->_next;
	printf("head<=>");
	while (p!=pHead)
	{
		printf("%d<=>", p->_data);
		p = p->_next;
	}
	printf("\n");
}

// 双向链表尾插
void ListPushBack(ListNode* pHead, LTDataType x)
{
	ListNode* s = (ListNode*)malloc(sizeof(ListNode));
	if (s == NULL)
	{
		perror("ListPushBack::");
		exit(1);
	}
	s->_data = x;
	s->_prev = pHead->_prev;
	s->_next = pHead;
	pHead->_prev->_next = s;
	pHead->_prev = s;
}

// 双向链表尾删
void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	if (pHead->_next == pHead)
	{
		printf("表空！\n");
		return;
	}
	ListNode* tail = pHead->_prev;
	pHead->_prev = tail->_prev;
	tail->_prev->_next = pHead;
	free(tail);
	tail = NULL;
}

// 双向链表头插
void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* s = new_node(x);
	s->_prev = pHead;
	s->_next = pHead->_next;
	pHead->_next->_prev = s;
	pHead->_next = s;
}

// 双向链表头删
void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	if (pHead->_next == pHead)
	{
		printf("表空！\n");
		return;
	}
	ListNode* front = pHead->_next;
	pHead->_next = front->_next;
	front->_next->_prev = pHead;
	free(front);
	front = NULL;
}

// 双向链表查找
ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	ListNode* p = pHead->_next;
	while (p != pHead)
	{
		if (p->_data == x)
		{
			return p;
		}
		p = p->_next;
	}
	return NULL;
}

// 双向链表在pos的前面进行插入
void ListInsert(ListNode* pos, LTDataType x)
{
	ListNode* s = new_node(x);
	s->_next = pos;
	s->_prev = pos->_prev;
	pos->_prev->_next = s;
	pos->_prev = s;
}

// 双向链表删除pos位置的节点
void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* next = pos->_next;
	next->_prev = pos->_prev;
	pos->_prev->_next = next;
	free(pos);
	pos = NULL;
}